import sqlite3
import json
from datetime import datetime
from config.log_config import AntLogger
from das.database_pool import DatabasePool

class DataDictionaryModel:
    """数据字典模型类"""
    def __init__(self, id=None, dict_key=None, dict_value=None, dict_desc=None, create_time=None, update_time=None):
        self.id = id
        self.dict_key = dict_key
        self.dict_value = dict_value
        self.dict_desc = dict_desc
        self.create_time = create_time
        self.update_time = update_time

class DataDictionaryDas:
    """数据字典数据访问服务类"""
    def __init__(self):
        self.db_pool = DatabasePool()
        self._create_table()
    
    def _create_table(self):
        """初始化数据字典表结构"""
        try:
            conn = self.db_pool.connect()
            cursor = conn.cursor()
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS data_dictionary (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    dict_key TEXT NOT NULL UNIQUE,
                    dict_value TEXT NOT NULL,
                    dict_desc TEXT,
                    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            conn.commit()
            cursor.close()
            conn.close()
            AntLogger.info('数据字典表创建/验证成功')
        except Exception as e:
            AntLogger.error(f'表结构初始化失败: {str(e)}')
    
    def get_all_entries(self):
        """获取全量字典数据"""
        try:
            conn = self.db_pool.connect()
            cursor = conn.cursor()
            cursor.execute('SELECT id, dict_key, dict_value, dict_desc, create_time, update_time FROM data_dictionary ORDER BY id')
            rows = cursor.fetchall()
            cursor.close()
            conn.close()
            
            result = []
            for row in rows:
                model = DataDictionaryModel(
                    id=row[0],
                    dict_key=row[1],
                    dict_value=row[2],
                    dict_desc=row[3],
                    create_time=row[4],
                    update_time=row[5]
                )
                result.append(model)
            
            AntLogger.info(f'获取数据字典记录成功，共{len(result)}条')
            return result
        except Exception as e:
            AntLogger.error(f'获取数据字典记录失败: {str(e)}')
            return []
    
    def get_by_key(self, key):
        """根据键获取字典数据"""
        try:
            conn = self.db_pool.connect()
            cursor = conn.cursor()
            cursor.execute('SELECT id, dict_key, dict_value, dict_desc, create_time, update_time FROM data_dictionary WHERE dict_key = ?', (key,))
            row = cursor.fetchone()
            cursor.close()
            conn.close()
            
            if row:
                model = DataDictionaryModel(
                    id=row[0],
                    dict_key=row[1],
                    dict_value=row[2],
                    dict_desc=row[3],
                    create_time=row[4],
                    update_time=row[5]
                )
                AntLogger.info(f'获取键为{key}的字典数据成功')
                return model
            else:
                AntLogger.warning(f'未找到键为{key}的字典数据')
                return None
        except Exception as e:
            AntLogger.error(f'获取键为{key}的字典数据失败: {str(e)}')
            return None
    
    def create_entry(self, dict_key, dict_value, dict_desc=None):
        """创建字典数据"""
        try:
            conn = self.db_pool.connect()
            cursor = conn.cursor()
            now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            cursor.execute(
                'INSERT INTO data_dictionary (dict_key, dict_value, dict_desc, create_time, update_time) VALUES (?, ?, ?, ?, ?)',
                (dict_key, dict_value, dict_desc, now, now)
            )
            last_id = cursor.lastrowid
            conn.commit()
            cursor.close()
            conn.close()
            
            AntLogger.info(f'创建字典数据成功，键={dict_key}')
            return last_id
        except Exception as e:
            AntLogger.error(f'创建字典数据失败: {str(e)}')
            return None
    
    def update_entry(self, dict_key, dict_value=None, dict_desc=None):
        """更新字典数据"""
        try:
            conn = self.db_pool.connect()
            cursor = conn.cursor()
            
            # 构建更新语句
            update_fields = []
            params = []
            
            if dict_value is not None:
                update_fields.append('dict_value = ?')
                params.append(dict_value)
            
            if dict_desc is not None:
                update_fields.append('dict_desc = ?')
                params.append(dict_desc)
            
            if not update_fields:
                AntLogger.warning('没有提供要更新的字段')
                return False
            
            # 添加更新时间
            update_fields.append('update_time = ?')
            params.append(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            
            # 添加条件参数
            params.append(dict_key)
            
            # 执行更新
            sql = f"UPDATE data_dictionary SET {', '.join(update_fields)} WHERE dict_key = ?"
            cursor.execute(sql, params)
            affected_rows = cursor.rowcount
            conn.commit()
            cursor.close()
            conn.close()
            
            if affected_rows > 0:
                AntLogger.info(f'更新字典数据成功，键={dict_key}')
                return True
            else:
                AntLogger.warning(f'未找到键为{dict_key}的字典数据，更新失败')
                return False
        except Exception as e:
            AntLogger.error(f'更新字典数据失败: {str(e)}')
            return False
    
    def delete_entry(self, dict_key):
        """删除字典数据"""
        try:
            conn = self.db_pool.connect()
            cursor = conn.cursor()
            cursor.execute('DELETE FROM data_dictionary WHERE dict_key = ?', (dict_key,))
            affected_rows = cursor.rowcount
            conn.commit()
            cursor.close()
            conn.close()
            
            if affected_rows > 0:
                AntLogger.info(f'删除字典数据成功，键={dict_key}')
                return True
            else:
                AntLogger.warning(f'未找到键为{dict_key}的字典数据，删除失败')
                return False
        except Exception as e:
            AntLogger.error(f'删除字典数据失败: {str(e)}')
            return False